<template>
  <div class="app-container">
    <!-- 分页查询 -->
    <el-form
      ref="queryParams"
      :model="queryParams"
      size="small"
      label-suffix=":"
      label-width="150px"
    >
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('goodsSKULang.skuCode')" prop="skuCode">
            <el-input
              v-model.trim="queryParams.skuCode"
              :placeholder="$t('pleaseEnter')"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('depotLang.depot')" prop="depotId">
            <el-select
              v-model="queryParams.depotId"
              :placeholder="$t('pleaseSelect')"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in depotOptionList"
                :key="item.value"
                :value="item.value"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item
            :label="$t('harvestLang.customerName')"
            prop="customerId"
          >
            <el-select
              v-model="queryParams.customerId"
              :placeholder="$t('pleaseSelect')"
              clearable
              filterable
              style="width: 200px"
            >
              <el-option
                v-for="item in customerOptionList"
                :key="item.value"
                :value="item.value"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('inventoryLang.markLack')" prop="markLack">
            <el-select v-model="queryParams.markLack" clearable :placeholder="$t('pleaseSelect')">
              <el-option :label="$t('inventoryLang.notMark')" :value="0" />
              <el-option :label="$t('inventoryLang.marked')" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('locationLang.locationCode')" prop="skuCode">
            <el-input
              v-model.trim="queryParams.locationCode"
              :placeholder="$t('pleaseEnter')"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('goodsSKULang.productCategory')"
            prop="categoryId"
          >
            <el-cascader
              v-model="queryParams.categoryId"
              :options="categoryAllList"
              :props="{
                label: 'categoryName',
                value: 'categoryId',
                children: 'children',
              }"
              style="width: 60%"
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleQuery"
          >
            {{ $t("query") }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t("reset") }}
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- 操作栏 -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-download"
          @click="exportToExcel"
        >
          {{ $t("warehousingLang.inventoryExport") }}
        </el-button>
      </el-col>
    </el-row>
    <!-- 数据列表 -->
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      border
      class="mt-10"
    >
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column
        :label="$t('tableIndex')"
        type="index"
        align="center"
        width="80"
      />
      <el-table-column
        :label="$t('goodsSKULang.baseSkuInfoDTO')"
        prop="skuCode,goodsName,categoryName"
        align="left"
        min-width="120"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("goodsSKULang.skuCode") + ":" }}
            <span>{{ scope.row.skuCode }}</span>
          </p>
          <p>
            {{ $t("goodsSKULang.goodsName") + ":" }}
            <span>{{ scope.row.goodsName }}</span>
          </p>
          <p>
            {{ $t("goodsSKULang.productCategory") }}:
            <span>{{ scope.row.categoryName }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('goodsSKULang.customerCodeAndName')"
        prop="customerCodeAndName"
        align="center"
        min-width="160"
      />
      <el-table-column
        :label="$t('goodsSKULang.depotCodeAndName')"
        prop="depotCodeAndName"
        align="center"
        min-width="120"
      />
      <el-table-column
        :label="$t('statusLang.pending')"
        prop="waitShelvingNum"
        align="center"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            :disabled="scope.row.waitShelvingNum === 0 ? true : false"
            @click="getWaitShelvingStockList(scope.row)"
          >{{ scope.row.waitShelvingNum }}</el-button>
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        :label="$t('statusLang.inLibrary')"-->
      <!--        prop="inStockNum"-->
      <!--        align="center"-->
      <!--        min-width="160"-->
      <!--      />-->
      <el-table-column
        :label="
          $t('statusLang.availableForSale') + '/' + $t('statusLang.freeze')
        "
        prop="canSellNum,freezeStock"
        align="center"
        min-width="120"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.canSellNum }}</span>
          <span>/</span>
          <span>{{ scope.row.freezeStock }}</span>
          <div v-if="scope.row.markLack">
            <el-tag type="danger">{{ $t('inventoryLang.markLack') }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('regionLang.badProduct')"
        prop="defectiveProductNum"
        align="center"
        min-width="120"
      />
      <el-table-column
        :label="$t('regionLang.staging')"
        prop="stagingNum"
        align="center"
        min-width="120"
      />
      <el-table-column
        :label="$t('locationLang.locationCode')"
        align="center"
        min-width="120"
      >
        <template slot-scope="scope">
          {{ formatLocationCodes(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('goodsSKULang.skuTotalNum')"
        prop="count"
        align="center"
        min-width="120"
      />
    </el-table>
    <!-- 页码 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 50, 100, 200, 1000, 2000, 5000]"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        @current-change="pageNoChange"
        @size-change="handleSizeChange"
      />
    </el-row>

    <!--  待上架库存 -->
    <el-dialog
      :title="$t('batchInventoryLang.pendingInventory')"
      :visible.sync="dialog"
      width="80%"
    >
      <el-table
        ref="form"
        v-loading="loading"
        :data="data"
        border
        class="mt-10"
      >
        <el-table-column
          :label="$t('tableIndex')"
          type="index"
          align="center"
          width="80"
        />
        <el-table-column
          :label="$t('inventoryLang.receiptDocument')"
          prop="orderNo"
          align="center"
          min-width="120"
        />
        <el-table-column
          :label="$t('statusLang.status')"
          prop="orderStatus"
          align="center"
          min-width="160"
        >
          <template slot-scope="scope">
            {{
              $t(
                "statusLang." +
                  getTitleByValue(deliveryStatusOptions, scope.row.orderStatus)
              )
            }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('goodsSKULang.skuCode')"
          prop="skuCode"
          align="center"
          min-width="120"
        />
        <el-table-column
          :label="$t('depotLang.depot')"
          prop="depotCodeAndName"
          align="center"
          min-width="120"
        />
        <el-table-column
          :label="$t('goodsSKULang.forecastQuantity')"
          prop="preSkuNum"
          align="center"
          min-width="160"
        />
        <el-table-column
          :label="$t('warehousingLang.receiptQuantity')"
          prop="receiptNum"
          align="center"
          min-width="120"
        />
        <el-table-column
          :label="$t('orderDate')"
          prop="orderCreatedDate"
          align="center"
          min-width="120"
        />
        <el-table-column
          :label="$t('receivingDate')"
          prop="inStockDate"
          align="center"
          min-width="120"
        />
      </el-table>
      <div style="margin-top: 20px">
        <el-row type="flex" justify="center">
          <el-button type="warning" plain @click="close">{{
            $t("close")
          }}</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllCategoryList } from '@/api/system/category'
import { getDepotListAllStatus } from '@/api/business/depotManage/depot'
import {
  getStockPageList,
  exportStockList,
  getWaitShelvingStockList,
  getCustomerNameList
} from '@/api/business/inventoryManage/inventory'
import { deliveryStatusDict } from '@/utils/dictData'
import { getTitleByValue, getDictOptionList } from '@/utils/dictUtils'
import * as XLSX from 'xlsx';
export default {
  name: 'Inventory',
  components: {},
  data() {
    return {
      loading: false,
      total: 0,
      categoryAllList: [], // 品类
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        categoryId: null, // 最低等级的种类id
        customerId: null,
        depotId: null,
        goodsName: null,
        skuCode: null,
        locationCode: null,
        markLack: null,
      },
      tableData: [],
      data: [],
      dialog: false,
      getTitleByValue: getTitleByValue,
      deliveryStatusOptions: getDictOptionList(deliveryStatusDict), // 状态
      depotOptionList: [], // 仓库下拉
      customerOptionList: [], // 客户名称下拉
      firstLevelCategoryList: [] // 一级品类
    }
  },
  created() {
    this.getDepotOptionList()
    this.getStockPageList()
    this.getCustomerNameList()
    this.getAllCategoryList()
  },
  methods: {
    // 查询
    handleQuery() {
      this.loading = true
      this.queryParams.pageNo = 1
      this.getStockPageList()
      this.loading = false
    },
    // 品类
    async getAllCategoryList() {
      const { data } = await getAllCategoryList()
      console.log(data, '品类')
      this.categoryAllList = data.categoryIdAndNameDTOList
    },
    handleChange(value) {
      console.log(value)
      this.queryParams.categoryId = value[2]
    },
    // 获取客户名称下拉
    async getCustomerNameList() {
      const { data } = await getCustomerNameList()
      console.log(data)
      this.customerOptionList = data
    },
    // 获取仓库下拉
    async getDepotOptionList() {
      const res = await getDepotListAllStatus()
      if (!res) return
      this.depotOptionList = res.data || []
    },
    // 获取库存列表
    async getStockPageList() {
      const { data } = await getStockPageList({
        ...this.queryParams
      })
      console.log(data, '分页查询')
      this.tableData = data.stockPageInfoDTOList
      this.total = data.totalRowNum
    },
    // 待上架库存
    async getWaitShelvingStockList(row) {
      this.dialog = true
      const { data } = await getWaitShelvingStockList({
        skuId: row.skuId,
        customerId: row.customerId
      })
      console.log(data, '待上架库存')
      this.data = data.stockForStatusDTOList
    },
    // 库存导出
    async handleExport() {
      const res = await exportStockList({})
      console.log(res, '库存导出')
    },
    pageNoChange(newPage) {
      this.queryParams.pageNo = newPage
      this.getStockPageList()
    },
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNo = 1
      this.getStockPageList()
    },
    async handleReset() {
      await this.$refs.queryParams.resetFields()
      this.getStockPageList()
    },
    close() {
      this.dialog = false
    },
    formatLocationCodes(row) {
      return row.locationCode ? row.locationCode.join(',') : '';
    },
    // 导出的方法
    exportToExcel() {
      const data = this.tableData;
      const fileName = '库存数据.xlsx';
      const workbook = XLSX.utils.book_new();
      const customHeaders = [
        '库位编号',
        '冻结库存',
        'SKU 编码',
        '产品名称',
        '产品总类',
        '客户id',
        '客户名称',
        '仓库id',
        '仓库名称',
        '在库数量',
        '待上架数量',
        '可售数量',
        '已打包数量',
        '不良品',
        '暂存区',
        '声明价值USD',
        '在途数量',
        '库位',
        'sku总数'
      ];
      const newData = data.map(item => {
        const newItem = {};
        customHeaders.forEach((header, index) => {
          const key = Object.keys(item)[index + 1];
          if (key === 'locationCode') {
            newItem[header] = item[key] ? item[key].join(',') : '';
          } else if (key !== 'skuId') {
            newItem[header] = item[key];
          } else {
            newItem[header] = item[key];
          }
        });
        return newItem;
      });
      const worksheet = XLSX.utils.json_to_sheet(newData, {
        header: customHeaders,
        skipHeader: false
      });
      // 自适应列宽
      const columnWidths = {};
      worksheet['!cols'] = [];
      customHeaders.forEach((header, index) => {
        const maxLength = newData.reduce((max, row) => Math.max(max, (row[header] || '').toString().length), 0);
        columnWidths[index] = maxLength < 10 ? 10 : maxLength;
        worksheet['!cols'].push({ wch: columnWidths[index] });
      });
      XLSX.utils.book_append_sheet(workbook, worksheet, '库存数据');
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      a.click();
      URL.revokeObjectURL(url);
    }

  }
}
</script>

<style></style>
